package no.nordicsemi.android.nrftoolbox;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import no.nordicsemi.android.nrftoolbox.utility.InputFilterMinMax;

public class AtModeActivity extends AppCompatActivity {

    String device_name;
    String mac_address;
    boolean isConnected = false;

    TextView devName;
    TextView devAddr;
    TextView connectState;
    TextView tagId;
    TextView tagFreq;
    TextView tagActthr;
    TextView tagActtime;
    TextView tagInactthr;
    TextView tagInacttime;
    TextView tagVot;
    TextView tagVer;
    TextView cfgvw;

    Spinner tagBoost;
    Spinner tagHbPeriod;
    Spinner tagAct;
    Spinner tagAccodr;
    Spinner tagFreq2;
    Spinner tagTime;
    Spinner tagMode;
    Spinner tagLed;
    Spinner tagLedS;
    Spinner tagCfg;
    Button tagAtv;
    Button tagW0;
    Button tagLit;
    Button leds;

    private String[] modeList;
    private String[] heartBeatList;
    private String[] actList;
    private String[] accodrList;
    private String[] freq2List;
    private String[] timeList;
    private String[] ledList;
    private String[] ledsList;

    private BluetoothLeService mBluetoothLeService;

    private int ledFreq = 5;
    private Map<String, String> prevCache = new HashMap<String, String>();


    public static final UUID WRITE_UUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    public static final UUID READ_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");

    private BluetoothGattCharacteristic writeCh;
    private BluetoothGattCharacteristic readCh;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            Log.d("mBluetoothLeService", "is null : " + (mBluetoothLeService == null));
            if (!mBluetoothLeService.initialize()) {
                Log.e("DCA_onServCon", "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            if(!isConnected)
                mBluetoothLeService.connect(mac_address);
            else {
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            Log.d("ACTION", action);
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                isConnected = true;
                updateConnectionState("Connected");
                invalidateOptionsMenu();
                Toast.makeText(AtModeActivity.this, "蓝牙连接成功!", Toast.LENGTH_SHORT).show();
                tagAtv.setEnabled(true);
                tagW0.setEnabled(true);
                tagLit.setEnabled(true);
                leds.setEnabled(true);

            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                isConnected = false;
                updateConnectionState("Disconnected");
                invalidateOptionsMenu();
                clearUI();
                Toast.makeText(AtModeActivity.this, "蓝牙连接断开!", Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                handleAtResponse(intent.getByteArrayExtra(BluetoothLeService.AT_DATA));
            }
        }
    };

    private void updateConnectionState(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                connectState.setText(String.valueOf(isConnected));
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_at_interact);
        Log.d("ATMOdeOnCreate", "oncreate");
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        device_name = bundle.getString("extra_device_name");
        mac_address = bundle.getString("extra_device_mac");
        String con = bundle.getString("isConnected");
        readCh = bundle.getParcelable("read_chara");
        writeCh = bundle.getParcelable("write_chara");
        isConnected = "true".equals(con);

        final Toolbar toolbar  = findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        Objects.requireNonNull(getSupportActionBar()).setTitle(mac_address);

        Intent gattServiceIntent = new Intent(this,BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        devName = (TextView) findViewById(R.id.device_name);

        devAddr = (TextView) findViewById(R.id.device_address);
        connectState = (TextView) findViewById(R.id.connection_state);
        tagAtv = (Button) findViewById(R.id.tag_atv);

        tagId = (TextView) findViewById(R.id.tag_id);
        tagMode = (Spinner) findViewById(R.id.tag_mode);
        tagFreq = (TextView) findViewById(R.id.tag_freq);
        tagBoost = (Spinner) findViewById(R.id.tag_boost);
        tagHbPeriod = (Spinner) findViewById(R.id.tag_hb_period);
        tagAct = (Spinner) findViewById(R.id.tag_act);
        tagAccodr = (Spinner) findViewById(R.id.tag_accodr);
        tagActthr = (TextView) findViewById(R.id.tag_actthr);
        tagActtime = (TextView) findViewById(R.id.tag_acttime);
        tagInactthr = (TextView) findViewById(R.id.tag_inactthr);
        tagInacttime = (TextView) findViewById(R.id.tag_inacttime);
        tagFreq2 = (Spinner) findViewById(R.id.tag_freq2);
        tagTime = (Spinner) findViewById(R.id.tag_time);
        tagVot = (TextView) findViewById(R.id.tag_vot);
        tagVer = (TextView) findViewById(R.id.tag_ver);
        tagLed = (Spinner) findViewById(R.id.tag_led);
        tagLedS = (Spinner) findViewById(R.id.tag_leds);
        tagW0 = (Button) findViewById(R.id.tag_w0);
        leds = (Button) findViewById(R.id.leds);

        tagLit = (Button) findViewById(R.id.tag_lit);

        cfgvw = (TextView) findViewById(R.id.cfg_vw);
        tagCfg = (Spinner) findViewById(R.id.tag_cfg);

        if(device_name.contains("CFG")) {
            cfgvw.setVisibility(View.VISIBLE);
            tagCfg.setVisibility(View.VISIBLE);
        }


        if(!isConnected) {
            clearUI();
        }

        modeList = getResources().getStringArray(R.array.mode_array);
        heartBeatList = getResources().getStringArray(R.array.heartbeat_array);
        actList = getResources().getStringArray(R.array.act_array);
        accodrList = getResources().getStringArray(R.array.accodr_array);
        freq2List = getResources().getStringArray(R.array.freq2_array);
        timeList = getResources().getStringArray(R.array.time_array);
        ledList = getResources().getStringArray(R.array.led_array);
        ledsList = getResources().getStringArray(R.array.leds_array);
        setGUI();

        tagAtv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //mBluetoothLeService.setCharacteristicNotification(readCh,true);
                Log.d("AT&V", "click at&v");
                mBluetoothLeService.writeData("AT&V\n",writeCh);
            }
        });



        tagW0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData("AT+W0\n",writeCh);
                Log.d("AT cmd", "AT+W0 sent");
            }
        });

        tagLit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int time = ledFreq;
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);

                mBluetoothLeService.writeData("AT+LED=1," + time + "\n",writeCh);
            }
        });

        leds.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBluetoothLeService.writeData(("AT+LEDS=?\n"), writeCh);
            }
        });


        tagMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+MODE") || prevCache.containsKey("AT+MODE") && prevCache.get("AT+MODE").equals(parent.getItemAtPosition(position)))
                    return;
                tagMode.setSelection(position);
                String cmd = ("AT+MODE=" + parent.getItemAtPosition(position) + "\n"); //String.valueOf(position) + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", (cmd));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // DO NOTHING
            }
        });

        tagBoost.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+BOOST") || prevCache.containsKey("AT+BOOST") && prevCache.get("AT+BOOST").equals(parent.getItemAtPosition(position)))
                    return;
                tagBoost.setSelection(position);
                String cmd = ("AT+BOOST=" + parent.getItemAtPosition(position) + "\n"); //String.valueOf(position) + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", (cmd));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagHbPeriod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+HB_PERIOD") || prevCache.containsKey("AT+HB_PERIOD") && prevCache.get("AT+HB_PERIOD").equals(parent.getItemAtPosition(position)))
                    return;
                tagHbPeriod.setSelection(position);
                String cmd = ("AT+HB_PERIOD=" + parent.getItemAtPosition(position).toString() + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagAct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+ACT") || prevCache.containsKey("AT+ACT") && prevCache.get("AT+ACT").equals(String.valueOf(position-1)))
                    return;
                tagAct.setSelection(position);
                String cmd = ("AT+ACT=" + String.valueOf(position-1) + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagAccodr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+ACCODR") || prevCache.containsKey("AT+ACCODR") && prevCache.get("AT+ACCODR").equals(String.valueOf(position-1)))
                    return;
                tagAccodr.setSelection(position);
                String cmd = ("AT+ACCODR=" + String.valueOf(position-1) + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagFreq2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+FREQ2") || prevCache.containsKey("AT+FREQ2") && prevCache.get("AT+FREQ2").equals(parent.getItemAtPosition(position)))
                    return;
                tagFreq2.setSelection(position);
                String cmd = ("AT+FREQ2=" + parent.getItemAtPosition(position).toString() + "\n");
//                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || !prevCache.containsKey("AT+TIME") || prevCache.containsKey("AT+TIME") && prevCache.get("AT+TIME").equals(parent.getItemAtPosition(position)))
                    return;
                tagTime.setSelection(position);
                String cmd = ("AT+TIME=" + parent.getItemAtPosition(position).toString() + "\n");
////                mBluetoothLeService.setCharacteristicNotification(readCh,true);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tagLed.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                if(position == 0)
//                    return;
                tagLed.setSelection(position);
                ledFreq = Integer.parseInt(ledList[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //未选中时候的操作
            }
        });

        tagLedS.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d("LEDS", "selected " + position);
                if(position == 0 || prevCache.containsKey("AT+LEDS") && parent.getItemAtPosition(position).equals(prevCache.get("AT+LEDS")))
                    return;
                else {
                    tagLedS.setSelection(position);
                    String cmd = ("AT+LEDS=" + parent.getItemAtPosition(position).toString() + "\n");
                    Log.d("LEDS", cmd);
                    mBluetoothLeService.writeData(cmd, writeCh);
                    Log.d("Sending", cmd);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选中时操作

            }
        });

        tagCfg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 )
                    return;
                tagCfg.setSelection(position);
                String cmd = ("AT+CONFIG_TYPE=" + parent.getItemAtPosition(position).toString() + "\n");
////                mBluetoothLeService.setCharacteristicNotification(readCh,true);
   //             Log.d("AT+CONFIG_TYPE", cmd);
                mBluetoothLeService.writeData(cmd,writeCh);
                Log.d("Sending", cmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

       // tagActthr.setFocusable(true);

        tagActthr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                et.setInputType(InputType.TYPE_CLASS_NUMBER);
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("加速度阈值(1~127)")
                        .setView(et)
                        .setNegativeButton("Cancel", null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if("".equals(et.getText().toString()))
                                    return;
                                int result = Integer.parseInt(et.getText().toString());
                                if(InputFilterMinMax.isInRang(1, 127,result)) {
                                    tagActthr.setText(String.valueOf(result));
                                    mBluetoothLeService.writeData("AT+ACTTHR=" + result + "\n", writeCh);
                                    Log.d("ACTTHR", "AT+ACTTHR=" + result + " sent...");
                                } else {
                                    new AlertDialog.Builder(et.getContext())
                                            .setTitle("输入值超出范围(1~127)")
                                            .setPositiveButton("CONFIRM", null)
                                            .show();
                                }

                            }
                        }).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showKeyBoard(et);
                    }
                },200);

            }
        });

        tagId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                //et.setText(tagId.getText().toString());
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("设备ID(HEX)")
                        .setView(et)
                        .setNegativeButton("Cancel",null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tagId.setText(et.getText().toString());
                                mBluetoothLeService.writeData("AT+ID=" + et.getText().toString() +"\n", writeCh);
                                Log.d("ID", "AT+ID=" + et.getText().toString() +" sent...");
                            }
                        }).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showKeyBoard(et);
                    }
                },200);
            }
        });

        tagFreq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                et.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
                //et.setText(tagFreq.getText().toString());
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("工作频率(HZ) (-30~50)")
                        .setView(et)
                        .setNegativeButton("Cancel", null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                try {
                                    if("".equals(et.getText().toString()))
                                        return;
                                    int result = Integer.parseInt(et.getText().toString());
                                    if(InputFilterMinMax.isInRang(-30,50, result)) {
                                        tagFreq.setText(String.valueOf(result));
                                        mBluetoothLeService.writeData("AT+FREQ=" + result + "\n", writeCh);
                                        Log.d("FREQ", "AT+FREQ=" + result + " sent...");
                                    } else {
                                        et.setText("");
                                        new AlertDialog.Builder(et.getContext())
                                                .setTitle("输入数据超出范围(-30~50)")
                                                .setPositiveButton("CONFIRM", null)
                                                .show();
                                    }
                                } catch(Exception ex) {
                                    et.setText("");
                                    new AlertDialog.Builder(et.getContext())
                                            .setTitle("输入数据格式错误")
                                            .setPositiveButton("CONFIRM", null)
                                            .show();
                                }
                            }
                        }).show();
               new Handler().postDelayed(new Runnable() {
                   @Override
                   public void run() {
                       showKeyBoard(et);
                   }
               },200);
            }
        });

        tagActtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                et.setInputType(InputType.TYPE_CLASS_NUMBER);
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("加速度计检测运动时间(1~31)")
                        .setView(et)
                        .setNegativeButton("Cancel",null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if("".equals(et.getText().toString()))
                                    return;
                                int result = Integer.parseInt(et.getText().toString());
                                if(InputFilterMinMax.isInRang(1,31, result)) {
                                    tagActtime.setText(String.valueOf(result));
                                    mBluetoothLeService.writeData("AT+ACTTIME="+result+"\n",writeCh);
                                    Log.d("ACTTIME", "AT+ACTTIME=" + result + " sent...");
                                } else {
                                    //et.setText("");
                                    new AlertDialog.Builder(et.getContext())
                                            .setTitle("输入数据超出范围(1~31)")
                                            .setPositiveButton("CONFIRM", null)
                                            .show();
                                }

                            }
                        }).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showKeyBoard(et);
                    }
                },200);
            }
        });

        tagInactthr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                et.setInputType(InputType.TYPE_CLASS_NUMBER);
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("加速度计静止阀值(1~127)")
                        .setView(et)
                        .setNegativeButton("Cancel", null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if("".equals(et.getText().toString()))
                                    return;
                                int result = Integer.parseInt(et.getText().toString());
                                if(InputFilterMinMax.isInRang(1,127,result)) {
                                    tagInactthr.setText(String.valueOf(result));
                                    mBluetoothLeService.writeData("AT+INACTTHR="+result+"\n", writeCh);
                                    Log.d("INACTTHR", "AT+INACTTHR=" + result + " sent...");
                                } else {
                                    new AlertDialog.Builder(et.getContext())
                                            .setTitle("输入数据超出范围(1~127)")
                                            .setPositiveButton("CONFIRM", null)
                                            .show();
                                }

                            }
                        }).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showKeyBoard(et);
                    }
                },200);

            }
        });

        tagInacttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = new EditText(AtModeActivity.this);
                et.setInputType(InputType.TYPE_CLASS_NUMBER);
                new AlertDialog.Builder(AtModeActivity.this)
                        .setTitle("加速度计检测静止时间(1~1023)")
                        .setView(et)
                        .setNegativeButton("Cancel", null)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if("".equals(et.getText().toString()))
                                    return;
                                int result = Integer.parseInt(et.getText().toString());
                                if(InputFilterMinMax.isInRang(1,1023,result)) {
                                    tagInacttime.setText(String.valueOf(result));
                                    mBluetoothLeService.writeData("AT+INACTTIME=" + result+"\n", writeCh);
                                    Log.d("INACTTIME", "AT+INACTTIME="  + et.getText().toString() + " sent...");
                                } else {
                                    new AlertDialog.Builder(et.getContext())
                                            .setTitle("输入数据超出范围(1~1023)")
                                            .setPositiveButton("CONFIRM", null)
                                            .show();
                                }

                            }
                        }).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showKeyBoard(et);
                    }
                },200);
            }
        });






    }


    public void setGUI() {
        devName.setText(device_name);
        devAddr.setText(mac_address);
        connectState.setText(String.valueOf(isConnected));
        if(!isConnected) {
            tagHbPeriod.setEnabled(false);
            tagAct.setEnabled(false);
            tagAccodr.setEnabled(false);
            tagFreq2.setEnabled(false);
            tagTime.setEnabled(false);
            tagMode.setEnabled(false);
            tagLed.setEnabled(false);
            leds.setEnabled(false);
            tagCfg.setEnabled(false);
        }
    }

    public void clearUI() {
        Toast.makeText(AtModeActivity.this, "clearUI", Toast.LENGTH_SHORT).show();
        tagId.setText(null);
        tagFreq.setText(null);
        tagActthr.setText(null);
        tagActtime.setText(null);
        tagInactthr.setText(null);
        tagInacttime.setText(null);
        tagVot.setText(null);
        tagVer.setText(null);

        tagHbPeriod.setEnabled(false);
        tagAct.setEnabled(false);
        tagAccodr.setEnabled(false);
        tagFreq2.setEnabled(false);
        tagTime.setEnabled(false);
        tagMode.setEnabled(false);
        tagLed.setEnabled(false);
        tagBoost.setEnabled(false);
        tagCfg.setEnabled(false);

        tagAtv.setEnabled(false);
        tagW0.setEnabled(false);
        tagLit.setEnabled(false);
        leds.setEnabled(false);

        tagMode.setSelection(0);
        tagHbPeriod.setSelection(0);
        tagAct.setSelection(0);
        tagAccodr.setSelection(0);
        tagFreq2.setSelection(0);
        tagTime.setSelection(0);
        tagLed.setSelection(0);
        tagLedS.setSelection(0);
        tagBoost.setSelection(0);
        if(tagCfg != null)
            tagCfg.setSelection(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if(mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mac_address);
            Log.d("DevConAct_onRes", "Connect request result = " + result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService((mServiceConnection));
        mBluetoothLeService = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.connect,menu);
        if(isConnected) {
            menu.findItem(R.id.menu_connect).setVisible(false);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(false);
        }
        return  true;

    }



    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home :
            {
                mBluetoothLeService.disconnect();
                onBackPressed();
                ////////////////////////////////////
//                Bundle bundle = new Bundle();
//                bundle.putBoolean("isConnected",isConnected);
//                bundle.putString("extra_device_name", device_name);
//                bundle.putString("extra_mac_address", mac_address);
//                //if(mBluetoothLeService != null) bundle.put
//                Intent intent = new Intent(AtModeActivity.this, DeviceControlActivity.class);
//                intent.putExtras(bundle);
//                startActivity(intent);
                ////////////////////////////////////
                break;
            }

            case R.id.menu_connect :
            {
                mBluetoothLeService.connect(mac_address);
                return true;
            }
            case R.id.menu_disconnect :
            {
                mBluetoothLeService.disconnect();
                return true;
            }
        }
        if(android.R.id.home == (item.getItemId())) {
            mBluetoothLeService.disconnect();
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {

            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();


            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                BluetoothGattCharacteristic tempCh = gattCharacteristic;
                String uuids = tempCh.getUuid().toString();

                Log.d("CHA", "'" + uuids +"'");
                if(uuids.equals(READ_UUID.toString())) {
                    //mBluetoothLeService.setReadCha(tempCh);
                    //mBluetoothLeService.readCharacteristic(tempCh);
                    readCh = tempCh;
                    mBluetoothLeService.setCharacteristicNotification(readCh,true);
                    Log.d("READ kEY", "DONE");
                }
                else if (uuids.equals(WRITE_UUID.toString())){
                    writeCh = tempCh;
                    Log.d("WRITE KEY", "DONE");
                }
            }
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("AT&V", "click at&v");
                mBluetoothLeService.writeData("AT&V\n",writeCh);
            }
        },500);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("AT+LEDS", "query for leds");
                mBluetoothLeService.writeData("AT+LEDS=?\n", writeCh);
            }
        },700);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("AT+LED", "send led");
                mBluetoothLeService.writeData("AT+LED=1,5\n",writeCh);
            }
        }, 1000);

    }

    void handleAtResponse(byte[] data) {
        String resp = new String(data);
        displayData(resp);
    }

    void displayData(String data) {
        Toast.makeText(AtModeActivity.this, data, Toast.LENGTH_SHORT).show();

        tagHbPeriod.setEnabled(true);
        tagBoost.setEnabled(true);
        tagAct.setEnabled(true);
        tagAccodr.setEnabled(true);
        tagFreq2.setEnabled(true);
        tagTime.setEnabled(true);
        tagMode.setEnabled(true);
        tagLed.setEnabled(true);
        tagCfg.setEnabled(true);

        String[] arr = data.split("\n");

        for (String ar : arr) {
            System.out.println(ar + ",");
            if (!ar.contains("="))
                continue;
            String[] a = ar.split("=");
            if (a.length > 1) {
                switch (a[0]) {
                    case "AT+ID":
                        tagId.setText(a[1]);
                        prevCache.put(a[0], a[1]);
                        break;

                    case "AT+MODE":
                        try{
                            if(Integer.parseInt(a[1]) >= 0 && Integer.parseInt(a[1]) <= 11) {
                                tagMode.setSelection(Integer.parseInt(a[1]) + 1);
                                prevCache.put(a[0], a[1]);
                            } else {
                                Toast.makeText(this, "MODE 非法参数", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.d("非法参数", "MODE 非法" + a[0]);
                            Toast.makeText(this, "MODE　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+FREQ":
                        try{
                            int x = Integer.parseInt(a[1]);
                            if(x >= -30 && x <=50) {
                                tagFreq.setText(a[1]);
                                prevCache.put(a[0], a[1]);
                            } else {
                                Toast.makeText(this, "FREQ 非法参数", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.d("非法参数", "FREQ 非法" + a[0]);
                            Toast.makeText(this, "FREQ　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+BOOST":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 5) {
                                tagBoost.setSelection(Integer.parseInt(a[1]));
                                prevCache.put(a[0], a[1]);
                            } else {
                                Toast.makeText(this, "BOOST 非法参数", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.d("非法参数", "BOOST 非法" + a[0]);
                            Toast.makeText(this, "BOOST　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+HB_PERIOD":
                        try {
                            tagHbPeriod.setSelection(findIndex(heartBeatList, a[1]));
                            prevCache.put(a[0], a[1]);
                        } catch (Exception ex) {
                            Log.d("非法参数", "HB_PERIOD 非法" + a[0]);
                            Toast.makeText(this, "HB_PERIOD　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+ACT":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if (x == 0 || x == 1 || x == 2) {
                                tagAct.setSelection(Integer.parseInt(a[1]) + 1);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "ACT 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "ACT 非法" + a[0]);
                            Toast.makeText(this, "ACT　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+ACCODR":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >=1 && x <=6) {
                                tagAccodr.setSelection(Integer.parseInt(a[1])+1);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "ACCORD 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "ACCORD 非法" + a[0]);
                            Toast.makeText(this, "ACCORD　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+ACTTHR":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 127) {
                                tagActthr.setText(a[1]);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "ACTTHR 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "ACTTHR 非法" + a[0]);
                            Toast.makeText(this, "ACTTHR　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+ACTTIME":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 31) {
                                tagActtime.setText(a[1]);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "ACTTIME 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "ACTTIME 非法" + a[0]);
                            Toast.makeText(this, "ACTTIME　参数异常", Toast.LENGTH_LONG).show();
                        }

                        break;
                    case "AT+INACTTHR":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 127) {
                                tagInactthr.setText(a[1]);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "INACTTHR 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "INACTTHR 非法" + a[0]);
                            Toast.makeText(this, "INACTTHR　参数异常", Toast.LENGTH_LONG).show();
                        }

                        break;
                    case "AT+INACTTIME":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 1023) {
                                tagInacttime.setText(a[1]);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "INACTTIME 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "INACTTIME 非法" + a[0]);
                            Toast.makeText(this, "INACTTIME　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+FREQ2":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 30) {
                                tagFreq2.setSelection(findIndex(freq2List, a[1]));
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "FREQ2 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "FREQ2 非法" + a[0]);
                            Toast.makeText(this, "FREQ2　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+TIME":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if((x >= 0 && x <= 5) || x == 10 || x == 20) {
                                tagTime.setSelection(findIndex(timeList, a[1]));
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "TIME 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "TIME 非法" + a[0]);
                            Toast.makeText(this, "TIME　参数异常", Toast.LENGTH_LONG).show();
                        }
                        Log.d("AT+TIME", a[0] + a[1]);
                        break;
                    case "AT+VOT":
                        tagVot.setText(a[1]);
                        prevCache.put(a[0], a[1]);
                        break;
                    case "AT+VER":
                        tagVer.setText(a[1]);
                        prevCache.put(a[0], a[1]);
                        break;
                    case "AT+LEDS":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 0 && x <= 4) {
                                tagLedS.setSelection(Integer.parseInt(a[1])+1);
                                prevCache.put(a[0], a[1]);
                            } else
                                Toast.makeText(this, "LEDS 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "LEDS 非法" + a[0]);
                            Toast.makeText(this, "LEDS　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "AT+CONFIG_TYPE":
                        try {
                            int x = Integer.parseInt(a[1]);
                            if(x >= 1 && x <= 3) {
                                if(tagCfg != null) {
                                    tagCfg.setSelection(Integer.parseInt(a[1]));
                                }
                            } else
                                Toast.makeText(this, "CONFIG_TYPE 非法参数", Toast.LENGTH_SHORT).show();
                        } catch(Exception ex) {
                            Log.d("非法参数", "CONFIG_TYPE 非法" + a[0]);
                            Toast.makeText(this, "CONFIG_TYPE　参数异常", Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        }
        prevCache.put("MAC", mac_address);
        prevCache.put("DEV_NAME", device_name);
    }

    public int findIndex(String[] arr, String x) {
        for (int i = 0; i < arr.length; i++) {
            if (x.equals(arr[i]))
                return i;
        }
        return -1;
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }


    void showKeyBoard(EditText editText) {
        if(editText != null) {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.showSoftInput(editText, 0);
        }
    }
}


